<template>
  <div id="cornerComment" v-if="dialogVisible">
    <div class="cornerComment-in">
      <div class="cornerComment-in-title">
        <span>{{ cornerDetail ? cornerDetail.name + '-' : '' }}实时区角</span>
        <div class="btn-time-line">
<!--          <el-button type="primary" plain size="small" @click="appointmentFn">开始计时</el-button>-->
<!--          <el-button type="danger" plain size="small" @click="appointmentFn">结束计时</el-button>-->
        </div>
        <span class="el-icon-circle-close close-Btn-line" @click="closePOpup"></span>
      </div>
      <div class="commentBody" ref="dialogBox">
        <div class="corner-a" :style="{height: boxHeight+'px'}">
          <div class="corner-left">
            <div class="corner-left-title">
              <div class="corner-left-title-list">今日预约（{{ studentList.length }}人）</div>
              <div class="corner-left-title-list">正常（{{ tabLength[1] }}人）</div>
              <div class="corner-left-title-list">离去（{{ tabLength[0] }}人）</div>
              <div class="corner-left-title-list">失约（{{ tabLength[3] }}人）</div>
              <div class="corner-left-title-list">设备状态：{{ deviceStatus }}</div>
            </div>
            <div class="corner-student" :style="{height: (boxHeight-50)+'px'}" v-if="studentList.length">
              <div class="corner-student-list" v-for="item in studentList" :key="item.id"
                   :style="{width: div_box_width+'px'}">
                <div class="corner-student-list-in" :style="{width: img_width+'px'}">
                  <div class="corner-student-list-postion"
                       :style="{height: (img_height+22)+'px',width: (img_width+2)+'px'}">
                    <div class="corner-student-list-img">
                      <div class="student-img-box"
                           :style="{background: 'url('+item.pic+')',backgroundRepeat: 'no-repeat',backgroundSize:'cover',backgroundPosition:'center', height: img_height+'px',width: img_width+'px'}"
                           :class="getStudentStatus(item.student_id)==3?'leaveUser':''">
                      </div>
                      <!-- in-color正常 lose-color失约 leave-coloe离去 not-color未预约-->
                      <!-- // 0离去1在线2未约3失约 getStudentStatus-->
                      <div class="student-status-title"
                           :class="getStudentStatus(item.student_id)==3?'lose-color':(getStudentStatus(item.student_id)==0?'leave-color':(getStudentStatus(item.student_id)==1?'in-color':''))">
                        <span v-if="getStudentStatus(item.student_id)==1">正常</span>
                        <span v-if="getStudentStatus(item.student_id)==3">失约</span>
                        <span v-if="getStudentStatus(item.student_id)==0">离去</span>
                      </div>
                    </div>
                    <div class="corner-student-list-evaluate"
                         :style="{height: (img_height+22)+'px',width: (img_width+2)+'px'}">
                      <div class="evaluate-l" :style="{height: (img_height+20)/2+'px',width: img_width/2+'px'}"
                           @click="studentCommonFn(1,item.student_id)">
                        <i class="iconfont iconpaizhao"></i>
                        <span>图文采集</span>
                      </div>
                      <div class="evaluate-r" :style="{height: (img_height+20)/2+'px',width: img_width/2+'px'}"
                           @click="studentCommonFn(2,item.student_id)">
                        <i class="iconfont iconshipin"></i>
                        <span>视频采集</span>
                      </div>
                      <div class="evaluate-b" :style="{height: (img_height+20)/2+'px',width: img_width+'px'}"
                           @click="studentCommonFn(3,item.student_id)">
                        <i class="iconfont iconxinxibianji"></i>
                        <span>学生点评</span>
                      </div>
                    </div>
                  </div>
                  <div class="corner-student-list-name">
                    <p>{{ item.student.name }}</p>
                    <p>{{ item.classes.class_name }}</p>
                  </div>
                </div>
              </div>
            </div>
            <div class="corner-student" :style="{height: (boxHeight-50)+'px'}" v-else>
              <p class="none-student-box">未找到相关数据</p>
            </div>
          </div>
          <div class="corner-right" :style="{width: div_box_width+'px'}">
            <div class="corner-left-title ">未预约：{{ tabLength[2] }}人</div>
            <div class="not-apply-box" :style="{height: (boxHeight-50)+'px'}">
              <div class="corner-student-list" v-for="item in activeDetail[2]" :key="item"
                   :style="{width: div_box_width+'px'}">
                <div class="corner-student-list-in" :style="{width: img_width+'px'}">
                  <div class="corner-student-list-postion"
                       :style="{height: (img_height+22)+'px',width: (img_width+2)+'px'}">
                    <div class="corner-student-list-img">
                      <div class="student-img-box"
                           :style="{background: 'url('+field+')',backgroundRepeat: 'no-repeat',backgroundSize:'cover',backgroundPosition:'center', height: img_height+'px',width: img_width+'px'}">
                      </div>
                      <!-- in-color正常 lose-color失约 leave-coloe离去 not-color未预约-->
                      <div class="student-status-title not-color">未预约</div>
                    </div>
                  </div>
                  <div class="corner-student-list-name">
                    <p>{{ item.name }}</p>
                    <p>{{ item.class ? item.class : '--' }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="cornerComment-in-footer">
        <el-button type="primary" @click="closePOpup" size="small">确定</el-button>
      </div>
    </div>
    <cornerCommon :visible.sync="cornerVisible" :studentId="studentId" :studentList="studentList"
                  :activeDetail="activeDetail" :cornerDetail="cornerDetail"></cornerCommon>
    <cornerCommonImg :visible.sync="cornerImgVisible" :studentId="studentId" :studentList="studentList"
                     :activeDetail="activeDetail" :cornerDetail="cornerDetail"
                     :commontType="commontType"></cornerCommonImg>
    <appointmentClass :visible.sync="appointmentVisible" :cornerDetail="cornerDetail"></appointmentClass>
  </div>
</template>

<script>
import field from '@/assets/imageAdmin/field.jpg';
import cornerCommon from "./cornerCommon";
import cornerCommonImg from "./cornerCommonImg";
import appointmentClass from "./appointment-class"
import {cornerTimeStudent} from '@/api/admin/corner'

export default {
  props: ['visible', 'detail'],
  components: {cornerCommon, cornerCommonImg, appointmentClass},
  data() {
    return {
      appointmentVisible: false,
      dialogVisible: false,
      cornerVisible: false,
      field: field,
      boxHeight: 0,
      div_box_width: 0,
      img_height: 0,
      img_width: 0,
      cornerImgVisible: false,
      cornerDetail: null, // 页面数据内容
      deviceStatus: '',
      ws: {},
      studentList: [],
      tabLength: [0, 0, 0, 0], // 区角学生状态数量
      activeDetail: {
        0: {},
        1: {},
        2: {},
        3: {}
      }, // 重组区角数据内容 0离去1在线2未约3失约
      studentId: 0,
      commontType: 0
    }
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible
      if (this.visible) {
        console.log('detail:', this.detail)
        let n = this;
        this.cornerDetail = JSON.parse(this.detail)
        // this.getSocket(this.cornerDetail.facility_code)
        this.cornerStudentFn() // 今日预约的学生
        this.$nextTick(() => {
          n.boxHeight = n.$refs.dialogBox.offsetHeight;
          n.boxWidth = n.$refs.dialogBox.offsetWidth; // 计算单个宽度 一排 8 个
          n.div_box_width = (n.boxWidth - 20) / 14; // 一寸照片 413*295
          // 单张的宽度 n.div_box_width*.9
          let a_width = n.div_box_width * .8;
          // img_height: 0,
          n.img_width = n.div_box_width * .8
          if (a_width < 295) {
            n.img_height = (a_width / 295) * 413
          }
          if (a_width === 295) {
            n.img_height = 413
          }
          if (a_width > 295) {
            n.img_height = (295 / a_width) * 413
          }
        })
      } else {
        this.studentList = [];
        this.tabLength = [0, 0, 0, 0];
        this.studentId = 0;
      }
    }
  },
  created() {

  },
  methods: {
    appointmentFn() {
      this.appointmentVisible = true
    },
    // socket对接=======================star
    getSocket(optionId) {
      let n = this;
      console.log('this.ws', this.ws, this.ws.readyState)
      if (this.ws.readyState === 1) {
        console.log('不需要去连接socket，直接发送区角mac给后台', optionId)
        this.loginsocket(optionId)
      } else {
        console.log('需要去连接socket')
        this.ws = new WebSocket('ws://' + thiis.$BASE_URL + ':8383')
      }

      this.ws.onmessage = function (res) {
        if (res.data === '1') {
          // console.log('登入成功进行区角推送：', res)
          n.loginsocket(optionId)
        } else {
          console.log('sockt消息推送来了', res)
          clearInterval(n.clearTimeFn) // 清空计时器
          // 5秒计时开始
          // n.clearTime = 0
          // n.getStudentTime() // 开始计时
          n.getCornerArrayFn(res.data)
          // console.log('收到的原始数据：', JSON.parse(res.data))
          // console.log('区角动态返回的数据', res)
        }
      }
      // 成功连上了socket
      this.ws.onopen = () => {
        console.log('成功连上了socket', optionId)
        n.deviceStatus = 'socket连接成功'
      }
      this.ws.onerror = function (err) {
        console.log('失败了ws', err)
        n.deviceStatus = 'socket连接失败'
      }
      this.ws.onclose = function (err) { // 关闭 websocket
        console.log('socket已经关闭了', err)
        n.deviceStatus = 'socket已关闭'
      }
    },
    // 初始化
    async InitFn() {
      console.log('页面请求的数据内容：', this.cornerOption)
      let option = {
        p: this.page.pageindex,
        class_id: this.cornerOption.class.id,
        corner_id: this.cornerOption.corner.id
      }
      let data = await this.$post(this.api.admin_corner_apply_list, option);
      console.log('data:', data)
      this.arryList = data.list.data
      this.page.total = data.list.total
    },
    // 对socket发送区角信息
    loginsocket(optionId) {
      console.log('发送区角信息到后台')
      this.ws.send(JSON.stringify({
        'mac': optionId,
        'type': 1
      }))
    },
    // 处理socket返回的数据
    getCornerArrayFn(option) {
      // 0离去1在线2未约3失约
      let activeDetail = {
        0: {},
        1: {},
        2: {},
        3: {}
      }
      // console.log('activeDetail:', activeDetail)
      if (option) {
        let a = JSON.parse(option)
        if (a instanceof Array) {
          console.log('收到的数据啊：', a)
          for (let i in a) {
            if (a[i].sum_time) {
              a[i].sum_time = a[i].sum_time ? this.formatSeconds(Number(a[i].sum_time)) : 0;
            }
            // 判断学生类型 activeName当前用户所在的tab
            if (Number(a[i].type) === Number(this.activeName)) {
              this.activeDetail[a[i].type][a[i].id] = this.getJson(a[i])
              this.$set(this.activeDetail, a[i].type, this.getJson(this.activeDetail[a[i].type]))
            }
            activeDetail[a[i].type][a[i].id] = this.getJson(a[i])
            // 此处需要判断是否需要进行正常的验证，比如正常的人离去，数据依旧残留
          }
          // 去除当前状态中不存在的学生,n 学生id
          for (let n in this.activeDetail[this.activeName]) {
            // 当前tab没有数据
            if (!Object.keys(activeDetail[this.activeName]).length) {
              this.activeDetail[this.activeName] = {}
            } else {
              if (!activeDetail[this.activeName][n]) {
                delete this.activeDetail[this.activeName][n]
              }
            }
          }
          // 各个状态的人数
          let listLength = [0, 0, 0, 0]
          for (let i in activeDetail) {
            if (Number(i) !== Number(this.activeName)) {
              this.activeDetail[i] = this.getJson(activeDetail[i])
            }
            listLength[i] = Object.keys(activeDetail[i]).length
          }
          this.tabLength = this.getJson(listLength)
          console.log('activeDetail处理实时数据内容：', this.activeDetail)
        }
      }
    },
    getJson(option) {
      return JSON.parse(JSON.stringify(option))
    },
    // 关闭弹窗
    closePOpup() {
      this.$emit('update:visible', false)
    },
    // 单天预约的学生
    async cornerStudentFn() {
      console.log(1111)
      // cornerTimeStudent({corner_id: this.cornerDetail.corner_id}).then(res=>{
      //   console.log('res:', res)
      //   for (let i in res.list) {
      //     res.list[i].pic = this.$openBASE_URL('img') + res.list[i].pic
      //   }
      //   this.studentList = res.list;
      // })
      let data = await this.$fetch(this.api.admin_corner_apply_student, {
        type: 2,
        corner_id: this.cornerDetail.corner_id,
        page: 0
      });
      for (let i in data.list.data) {
        data.list.data[i].pic = this.$openBASE_URL('img') + data.list.data[i].pic
      }
      this.studentList = data.list.data;
      console.log(123, this.studentList)
    },
    // 判断获取学生状态
    getStudentStatus(id) {
      // 0离去1在线2未约3失约
      // activeDetail: {
      //   0: {},
      //   1: {},
      //   2: {},
      //   3: {}
      // }, // 重组区角数据内容 0离去1在线2未约3失约
      let status = 3 // 一开始未到都算失约
      for (let index in this.activeDetail) {
        if (this.activeDetail[index][id]) {
          status = index
        }
      }
      return status
    },
    studentCommonFn(type, student_id) {
      // type 1 图文采集 2 视频采集 3 学生点评
      this.commontType = type;
      this.studentId = student_id;
      if (type === 3) {
        this.cornerVisible = true;
      } else {
        this.cornerImgVisible = true;
      }
    }
  },
  mounted() {
  }
}
</script>
<style scoped>
#cornerComment {
  height: 100vh;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, .5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9;
}

.cornerComment-in {
  width: 92%;
  height: 92%;
  background: #fff;
  display: flex;
  flex-direction: column;
  border-radius: 5px;
}

.cornerComment-in-title {
  height: 50px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ddd;
  font-size: 24px;
}

.cornerComment-in-title span {
  padding: 0 10px;
}

.cornerComment-in-title span:first-child {

  font-size: 16px;
}

.btn-time-line {
  flex: 1;
  text-align: center;
}

.cornerComment-in-footer {
  height: 50px;
  border-top: 1px solid #ddd;
  display: flex;
  align-items: center;
  padding: 0 10px;
  justify-content: center;
}

.commentBody {
  /*padding: 0 10px;*/
  flex: 1;
  overflow-y: auto;
}

.close-Btn-line {
  cursor: pointer;
}

.corner-a {
  display: flex;
}

.corner-left {
  flex: 1;
}

.corner-left-title {
  height: 50px;
  display: flex;
  align-items: center;
  padding-left: 10px;
}

.corner-left-title-list {
  padding-right: 20px;
  color: #777;
  font-weight: bold;
  font-size: 15px;
}

.corner-left-title-list:first-child {
  color: #1b8de5;
}

.corner-right {
  background: #f8f8f8;
  height: 100%;
}

.corner-student {
  overflow-y: auto;
  padding-left: 10px;
}

.corner-student-list {
  float: left;
  margin-bottom: 10px;
  margin-top: 10px;
}

.corner-student-list-in {
  cursor: pointer;
}

.corner-student-list-in:hover .corner-student-list-postion {
  box-shadow: 0 0 4px #1b8de5;
}

.corner-student-list-postion {
  position: relative;
  border: 1px solid #ddd;
}

.corner-student-list-img {
  position: absolute;
}

.corner-student-list:hover .corner-student-list-evaluate {
  display: block;
}

.corner-student-list-evaluate {
  width: 100%;
  height: 100%;
  position: absolute;
  display: none;
  background: rgba(0, 0, 0, .6);
  color: #fff;
}

.corner-student-list-evaluate i {
  font-size: 34px;
  margin: 0;
}

.corner-student-list-evaluate span {
  font-size: 10px;
}

.evaluate-l {
  float: left;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  border-right: 1px solid #f8f8f8;
  justify-content: center;
  flex-direction: column;
}

.evaluate-r {
  float: left;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  justify-content: center;
  flex-direction: column;
}

.evaluate-b {
  float: left;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  justify-content: center;
  border-top: 1px solid #fff;
  flex-direction: column;
}

.student-status-title {
  height: 20px;
  text-align: center;
  color: #fff;
}

.corner-student-list-name {
  text-align: center;
}

.corner-student-list-name p:first-child {
  padding-top: 5px;
  font-size: 16px;
}

.corner-student-list-name p:last-child {
  font-size: 12px;
  color: #999;
}

.in-color {
  background: #1b8de5;
}

.lose-color {
  background: #ef6f14;
}

.leave-color {
  background: #444;
}

.not-color {
  background: #e28fad;
}

.not-apply-box {
  overflow-y: auto;
  padding-left: 10px;
}

.leaveUser {
  opacity: .4;
}

.none-student-box {
  padding: 100px 0;
  text-align: center;
  font-size: 18px;
  color: #999;
}
</style>


